package com.thb.pay.manage.comm.shiro.realm;

import com.google.common.collect.Lists;
import com.thb.pay.manage.comm.enums.LoginTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.realm.Realm;

import java.util.Collection;
import java.util.List;

/**
 * @author lucky
 */
@Slf4j
public class MyModularRealmAuthenticator extends ModularRealmAuthenticator {
    @Override
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        System.out.println("UserModularRealmAuthenticator:method doAuthenticate() execute ");
        // 1.判断getRealms()是否返回为空
        assertRealmsConfigured();
        // 2.强制转换回自定义的CustomizedToken
        // 3.获取登录类型
        LoginTypeEnum loginType = null;
        // 4.所有Realm
        Collection<Realm> realms = getRealms();
        // 登录类型对应的所有Realm
        List<Realm> typeRealms = Lists.newArrayList();
        for (Realm realm : realms) {
            if (realm.getName().contains(loginType.name())) {
                typeRealms.add(realm);
            }
        }
        // 判断是单Realm还是多Realm
        if (typeRealms.size() == 1) {
            log.debug("doSingleRealmAuthentication() execute ");
            return doSingleRealmAuthentication(typeRealms.get(0), null);
        } else {
            log.debug("doMultiRealmAuthentication() execute ");
            return doMultiRealmAuthentication(typeRealms, null);
        }
    }
}